<?php

namespace app\models;

use Yii;
use yii\base\Model;

/**
 * LoginForm is the model behind the login form.
 */
class RegisterForm extends Model {

    public $username;
    public $email;
    public $password;
    public $password_confirm;

    /**
     * @return array the validation rules.
     */
    public function rules() {
        return [
            // username and password are both required
            [['username', 'email', 'password', 'password_confirm'], 'required'],
            // email must be a email value
            ['email', 'email'],
            // password is validated by validatePassword()
            ['username', 'validateUsername'],
            ['email', 'validateEmail'],
            ['password', 'validatePassword'],
        ];
    }

    /**
     * Validates the password.
     * This method serves as the inline validation for password.
     *
     * @param string $attribute the attribute currently being validated
     * @param array $params the additional name-value pairs given in the rule
     */
    public function validatePassword($attribute, $params) {
        if (!$this->hasErrors()) {
            $password = $this->password;
            $password_confirm = $this->password_confirm;

            if ($password != $password_confirm) {
                $this->addError($attribute, '两次输入的密码不一样.');
            }
        }
    }

    /**
     * 验证用户名
     */
    public function validateUsername($attribute, $params) {
        if (!$this->hasErrors()) {
            $user = User::findByUsername($this->username);
            if ($user) {
                $this->addError($attribute, '该用户名已经存在.');
            }
        }
    }

    /**
     * 验证密码
     */
    public function validateEmail($attribute, $params) {
        if (!$this->hasErrors()) {
            $user = User::findByEmail($this->email);
            if ($user) {
                $this->addError($attribute, '该邮箱已经注册.');
            }
        }
    }

    /**
     * Logs in a user using the provided username and password.
     * @return boolean whether the user is logged in successfully
     */
    public function register() {
        if ($this->validate()) {
            //写入数据库
            $user = new Users();
            $user->username = $this->username;
            $user->email = $this->email;
            $user->password = $this->password;
            $user->status = '1';
            $user->save();
            return true;
        } else {
            return false;
        }
    }

    /**
     * 给字段添加label名字
     */
    public function attributeLabels() {
        return [
            'username' => '用户名',
            'email' => '邮箱',
            'password' => '密码',
            'password_confirm' => '再次输入密码',
        ];
    }

}
